<?php

/**
 商品分类关联控制器 datetime：2016-11-9 19:43 @auth YWH
 */

namespace Admin\Controller;
use Think\Controller;
class GoodstypeController extends Controller
{
	
    public function index()
    {
            $Goodstype = D('Goodstype');

            //初始化变量
            $where = '';
            $order = '';
            $limit = '';

            $order = empty($order)?'pid':$order;

        //搜索设置
            if(I('get.keywords')){
                $where = "type_name like '%".I('get.keywords')."%'";
            }else{
                $where = '';
            }

            //设置分页
            //记录总数
            $count = $Goodstype->where($where)->count();

           //每页显示的记录条数
            $p = I('get.num') ? I('get.num') : 5;

            if ($count<=5&&$count>3) {
                
                $p = floor($count/2);
            }elseif ($count<=3&&$count>1) {
                
                $p = $count-1;
            }elseif ($count<=2) {
                $p = 1;
            }

            $num = $p;
            
            //创建分页对象
            $page = new \Think\Page($count,$num);
            //显示分页
            $show = $page->show();
            //设置limit参数
            $limit = $page->firstRow.','.$page->listRows;

            //查询
            $goodsclasses = $Goodstype->where($where)->order($order)->limit($limit)->select();


            $totalPage=ceil($count/$num); 

            //pid=>父类名
            foreach ($goodsclasses as $k => $v)
            {     
                if($goodsclasses[$k]['pid']==0)
                {
                    $goodsclasses[$k]['pid'] = '顶级分类';
                }else{
                    $parent = $Goodstype->where("pid=".$goodsclasses[$k]['pid'])->find();//以pid查找父类数据
                    $pathLength = count(explode(',',$goodsclasses[$k]['path']));//以'，'计算路径深度
                    $goodsclasses[$k]['pid']= str_repeat('|----', $pathLength-2).$parent['type_name'];//根据路径深度添加路径标识符

                }
        }

            $this->assign('goodsclasses',$goodsclasses);

            $this->assign('page', $show);//输出页码

            $this->assign('totalPage', $totalPage);

            $this->display();
    }




   	 public function add()//显示添加页
     {  


        $Goodstype = D('Goodstype');//查询分类，填充option
        //查询
        $goodsclasses = $Goodstype->order('pid')->select();

        $this->assign('goodsclasses',$goodsclasses);
      
        $this->display();
    }





    public function insert()
    {   

        if (empty(session('phoneCode'))) {
          
            $this->error('尚未验证手机',U('Goodstype/index'),2);
            
        }



        if (empty($_POST['type_name'])) {
            
             redirect(U('Admin/Goodstype/add'), 2, '分类名称不能为空');

            exit();

        }

    	
        $goods      = D('Goodstype');//新的分类添加

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg','JPEG');// 设置附件上传类型
        $upload->rootPath = 'Public/Uploads/'; // 设置附件上传根目录
        // 上传单个文件
        $info = $upload->uploadOne($_FILES['img']);
        if(!$info) {// 上传错误提示错误信息
        $this->error($upload->getError());
        exit();
        }else{// 上传成功 获取上传文件信息
          $img = $info['savepath'].$info['savename'];
        }




        if ($goods->create())
        {
            
           $type_name   = I('post.type_name');
           $pid         = I('post.pid');

           if ($pid == 0)
           {
              
               $path    = '0,';
           }else{

            $id=$goods->getLastInsId()+1;
            $lastPath    = $goods->find(I('post.pid'));

            $path        = $lastPath['path'].$id.',';
           }


           $data = ['type_name' => $type_name,'pid'=> $pid,'path'=>$path,'img'=>$img];


           if ($goods->add($data)>0) 
           {

              $this->success('分类添加成功!',U('Admin/Goodstype/add'),2);

           }else{

            $this->error('分类添加失败!',U('Admin/Goodstype/add'),2);
        }

           
                    
        }else{

            $this->error($goods->getError(),'',2);
           exit();
        }

        
           
    }



    public function edit()
    {

        if (I('get.id')=='') {//有无id
            
            redirect(U('Admin/Goodstype/index'), 2, '非法操作');
            exit();
        }




         $Goodstype     = D('Goodstype');

         $goodstypes    = $Goodstype->find(I('get.id'));

         $goodsclasses  = $Goodstype->select();

                 
         // var_dump($goodstypes);
        
         $this->assign('goodstypes',$goodstypes);
         $this->assign('goodsclasses',$goodsclasses);

         $this->display();
    }



    public function modify()//update
    {

        if (empty($_POST) || empty($_GET['id'])||empty($_POST['type_name'])) 
        {//判断是否携带必须的数据
            
            redirect(U('Admin/Goodstype/index'), 2, '非法操作');

            exit();
            
        }

         $goods = D('Goodstype');

        $id             = $goods->getLastInsId()+1;
        $good           = $goods->find(I('get.id'));

        $parentInfo     = $goods->find($good['id']);


        if($parentInfo['path']== 0)
        {
            $path                  = 0;

            $_POST['pid']          = 0;

        }else{

            $path = $parentInfo['path'].','.$parentInfo['id'];
        }
        

        $data        = ['id'=>I('get.id'),'type_name'=>$type_name,'pid'=>I('post.pid'),'status'=>I('post.status'),'path'=>$path];



        if ($goods->validate(false)->create($data)) 
        {
           if ($goods->save()) 
           {
               
            $this->success('更新成功', '/Admin/Goodstype/index');
            
           }else{

            $this->error('更新失败','Admin/Goodstype/index');

           }
        }else{

             $this->error($goods->getError(),'',2);

             exit();
        }

    }



    public function  del(){

        if (empty($_GET['id'])) {
            
            $this->error('非法操作','/Admin/Goodstype/index',2);
        }

       $goods = D('Goodstype');

        

        if ($goods->delete($_GET['id'])>0) {
            

             $this->success('删除成功', '/Admin/Goodstype/index');
                
           }else{

            $this->error('删除失败','Admin/Goodstype/index');

           }


        }




                 /**
 容联云
 */
    public  function  yzm()
 {
        $phonenum=I('post.phone');    
        $yzm=mt_rand(1000,9999);
         // 主帐号,对应开官网发者主账号下的 ACCOUNT SID
        $accountSid= '8a216da8586c737901586ccb15d60064';

        //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
        $accountToken= 'f6c7df7a246f44358961eddd721867d9';

        //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
        //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
        $appId='8a216da8586c737901586ccb178e006b';

     //请求地址
        //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
        //生产环境（用户应用上线使用）：app.cloopen.com
        $serverIP='app.cloopen.com';

        //请求端口，生产环境和沙盒环境一致
        $serverPort='8883';

        //REST版本号，在官网文档REST介绍中获得。
        $softVersion='2013-12-26';

         // 初始化REST SDK
         // global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;
         $rest = new \Org\Util\REST($serverIP,$serverPort,$softVersion);
         $rest->setAccount($accountSid,$accountToken);
         $rest->setAppId($appId);

         // 发送模板短信1

         $data['code'] =$yzm;

         $result = $rest->sendTemplateSMS($phonenum,array($data['code'],'1'),'1');
         if($result == NULL ) {
             echo "result error!";
             // break;
         }
         if($result->statusCode!=0) {
             echo "error code :" . $result->statusCode . "<br>";
             echo "error msg :" . $result->statusMsg . "<br>";
             //TODO 添加错误处理逻辑
         }else{
            
             // 获取返回信息
            $smsmessage = $result->TemplateSMS;
            
            session('phoneCode',$yzm);

            $this->ajaxReturn(['code'=>'1']);
          
             //TODO 添加成功处理逻辑
         }
 }



}